import React, { useState, useEffect } from 'react';
import { Card, Typography, Button, InputNumber } from 'antd';

const { Title, Paragraph, Text } = Typography;

const InterviewQuestion = ({ question, onFinish, timePerQuestion }) => {
  const [showAnswer, setShowAnswer] = useState(false);
  const [timer, setTimer] = useState(null);
  const [score, setScore] = useState(0);

  useEffect(() => {
    setTimer(
      setTimeout(() => setShowAnswer(true), timePerQuestion * 60 * 1000)
    );
    return () => {
      clearTimeout(timer);
    };
  }, [question, timePerQuestion]);

  const handleFinishClick = () => {
    setShowAnswer(true);
    clearTimeout(timer);
  };

  const handleNextClick = async () => {
    // 发送 PUT 请求
    try {
      const response = await fetch(
        `http://localhost:29157/api/tools/testDb/${question.id}/score`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ score }),
        }
      );

      if (!response.ok) {
        throw new Error('Error updating the score.');
      }
    } catch (error) {
      console.error('Error sending the score to the backend:', error);
    }

    onFinish();
    setShowAnswer(false);
    setScore(0);
  };

  return (
    <div>
      <Card>
        <Title level={4}>{question.question}</Title>
        <Paragraph>
          <Text type='secondary'>
            类型：{question.questionType} | 来源：{question.source} | 难度：
            {question.difficulty}
          </Text>
        </Paragraph>
        {showAnswer ? (
          <>
            <Paragraph>
              <Text type='danger'>答案：</Text>
              {question.answer}
            </Paragraph>
            <Paragraph>
              <Text>评分：</Text>
              <InputNumber
                min={0}
                max={10}
                value={score}
                onChange={value => setScore(value)}
              />
            </Paragraph>
            <Button
              onClick={handleNextClick}
              style={{ marginTop: '1rem' }}>
              下一题
            </Button>
          </>
        ) : (
          <Button onClick={handleFinishClick}>结束答题</Button>
        )}
      </Card>
    </div>
  );
};

export default InterviewQuestion;
